﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PatientManagement.Database;
using PatientManagement.Managers;

namespace PatientManagement
{
    public partial class FormSearchPatient : Form
    {
        public int PatientId = -1;
        private List<Patient> Patients;

        public FormSearchPatient()
        {
            InitializeComponent();
            InitControl();
            GetPatients();
        }

        private void InitControl()
        {
            dtgPatient.AutoGenerateColumns = false;
            colSex.DataSource = new List<object> { new { Id = true, Value = "Nam" }, new { Id = false, Value = "Nữ" } };
            colSex.ValueMember = "Id";
            colSex.DisplayMember = "Value";
        }

        private void GetPatients()
        {
            Patients = ServiceManager.Instance.GetAllPatients();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            var filterData = Patients;
            if (!string.IsNullOrEmpty(tbPatientId.Text))
            {
                filterData = filterData.Where(x =>
                    x.PatientId != null && x.PatientId.ToLower().Contains(tbPatientId.Text.ToLower())
                ).ToList();
            }
            if (!string.IsNullOrEmpty(tbName.Text))
            {
                filterData = filterData.Where(x => x.Name.ToLower().Contains(tbName.Text.ToLower())).ToList();
            }
            if (!string.IsNullOrEmpty(tbAddress.Text))
            {
                filterData = filterData.Where(x => x.Address.ToLower().Contains(tbAddress.Text.ToLower())).ToList();
            }

            dtgPatient.DataSource = filterData;
        }

        private void dtgPatient_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (dtgPatient.Columns["colChoose"].Index == e.ColumnIndex)
                {
                    PatientId = Convert.ToInt32(dtgPatient["colId", e.RowIndex].Value);
                    this.Close();
                }

                if (e.ColumnIndex == dtgPatient.Columns["colPrescription"].Index)
                {
                    int patientId = Convert.ToInt32(dtgPatient["colId", e.RowIndex].Value);
                    FormPrescriptionManagement form = new FormPrescriptionManagement(patientId);
                    form.ShowDialog();
                }
            }
        }
    }
}
